/*
 * 
 */
package com.csliubo.eclipse.plugin.sqlgenerator.core.resultset;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.csliubo.eclipse.plugin.sqlgenerator.core.model.Row;

/**
 * 抽象结果集处理
 * 
 * @author liubo.cs@hotmail.com
 * @version 1.0
 */
public abstract class AbstraceResultSetHandler implements ResultSetHandler {

    public List<Row> convertResultSetToRows(ResultSet rs) throws SQLException {
        ResultSetMetaData data = rs.getMetaData();
        int count = data.getColumnCount();
        List<Row> rows = new ArrayList<Row>();
        Row row = new Row();
        for (int i = 1; i <= count; i++) {
            row.addColumn(data.getColumnName(i));
        }
        rows.add(row);
        while (rs.next()) {
            row = new Row();
            for (int i = 1; i <= count; i++) {
                Object obj = rs.getObject(i);
                if (null != obj) {
                    row.addColumn(obj.toString());
                    continue;
                } else {
                    int type = data.getColumnType(i);
                    row.addColumn(getValueForNull(type));
                }
            }
            rows.add(row);
        }
        return rows;
    }

    /**
     * 对null的处理，对于wiki来说需要根据类型返回值，而对于excel来说，只要返回null即可
     * @param type
     * @return
     */
    abstract protected String getValueForNull(int type);
}
